<?php

namespace App\Services;

use App\Helpers\Tools;
use EasyWeChat\Factory;

class WeChatProgramService
{
    protected $config;
    protected $payConfig;

    public function __construct()
    {
        $this->config = [
            'app_id' => 'wx819e5b6b61713c32',
            'secret' => '32914b04c831dddc42ce1e6b4f79b454',
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => __DIR__ . '/wechat.log',
            ],
        ];

        $this->payConfig = [
            'app_id' => 'wx819e5b6b61713c32',
            'mch_id' => '1486467912',
            'key' => '32914b04c831dddc42ce1e6b4f79b454',
            'cert_path' => public_path('cert/apiclient_cert.pem'), // XXX: 绝对路径！！！！
            'key_path' => public_path('cert/apiclient_key.pem'),      // XXX: 绝对路径！！！！
            'notify_url' => 'https://calculate.bestpeng.com/api/wechat/notify',
        ];
    }

    /**
     * 微信小程序获取openid
     *
     * @param string $code
     *
     * @return array
     */
    public function login($code)
    {
        $app = Factory::miniProgram($this->config);
        $info = $app->auth->session($code);

        return $info;
    }

    /**
     * 微信小程序解密
     *
     * @param string $code
     *
     * @return array
     */
    public function decryptData($session, $iv, $encryptData)
    {
    Tools::logInfo($session);
    Tools::logInfo($iv);
    Tools::logInfo($encryptData);
        $app = Factory::miniProgram($this->config);
        $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptData);
        return $decryptedData;
    }

    public function pay($params)
    {
        $app = Factory::payment($this->payConfig);

        $result = $app->order->unify([
            'body' => $params['body'],
            'out_trade_no' => $params['out_trade_no'],
            'spbill_create_ip' => $this->getIp(),
            'total_fee' => $params['money'],
            'notify_url' => 'https://calculate.bestpeng.com/api/wechat/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI',
            'openid' => $params['openid'],
        ]);

        $result['time_stamp'] = time();
        $result['sign'] = $this->paySign($result);

        return $result;

    }

    /**
     * 获取用户真实ip
     *
     * @author 日隆
     *
     */
    protected function getIp()
    {
        $ip = !empty($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : (!empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown'));
        return $ip;
    }

    /**
     * 生成数字和字母组合随机数
     *
     * @author 日隆
     *
     */
    function randomkeys($length)
    {
        $returnStr = '';
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for ($i = 0; $i < $length; $i++) {
            $returnStr .= $pattern{mt_rand(0, 61)};
        }

        return $returnStr;
    }

    /**
     * 生成小程序支付签名
     *
     * @author 日隆
     *
     */
    function paySign($data, $key = 'ewqrqrsagfdsafaweweqr12AAAAAAAAA')
    {
        $args = [];
        $args['appId'] = $data['appid'];
        $args['nonceStr'] = $data['nonce_str'];
        $args['package'] = 'prepay_id=' . $data['prepay_id'];
        $args['signType'] = 'MD5';
        $args['timeStamp'] = $data['time_stamp'];

        ksort($args);
        $stringA = '';

        foreach ($args as $k => $v) {
            $stringA .= $k . '=' . $v . '&';
        }

        $stringSignTemp = $stringA . 'key=' . $key;
        $signature = md5($stringSignTemp);

//        $newString = $stringA . 'signature=' . $signature;
//        $newSign = base64_encode($newString);

        return $signature;
    }

}